#include "ADC.h"

Typedef_ADC ADC;

void ADC_SelChannel(uint8 chn)
{
    if(chn != ADC.Channel)
    {
        uint8 tmp;

        tmp = ADCON1;
        tmp &= 0b10111111;
        tmp |= (chn<<2)&0b01000000;
        ADCON1 = tmp;

        tmp = ADCON0;
        tmp &= 0b11000011;
        tmp |= (chn<<2)&0b00111100;

        ADC.Channel = chn;
        _delay(100);
    }
}

void initADC(void)
{
    ADCON1 = C_DEFAULT_ADCON1;
    ADCON0 = C_DEFAULT_ADCON0;

    ADC.Channel = ADC_CH_VBG;
}

void DeInitADC(void)
{
    ADCON0 = 0;
    ADCON1 = 0;
}

#if 0
uint16 ADConverter(void)
{
	unsigned char i = 128;

    RB3 = 1;
    GODONE = 1;						//开始转换

	while(GODONE)
	{
		if(0 == (--i))		//延时6.4ms仍没有AD转换结束，跳出程序
			return;
	}
	
    if(ADFM == 0)
    	ADC.Result=(ADRESH<<4)+(ADRESL>>4);	//计算12位AD值
    else 
    {
        ADC.Result=ADRESH;
        ADC.Result=ADC.Result<<8;
        ADC.Result+=ADRESL;
    }

    RB3 = 0;

    return ADC.Result;
}
#else
uint8 ADConverter(void)
{
	unsigned char i = 128;

    GODONE = 1;						//开始转换

	while(GODONE)
	{
		if(0 == (--i))		//延时6.4ms仍没有AD转换结束，跳出程序
			return 0;
	}
	
    // if(ADFM == 0)
    // 	ADC.Result=(ADRESH<<4)+(ADRESL>>4);	//计算12位AD值
    // else 
    // {
    //     ADC.Result=ADRESH;
    //     ADC.Result=ADC.Result<<8;
    //     ADC.Result+=ADRESL;
    // }
    ADC.Result = ADRESH;
    return ADC.Result;
}
#endif

uint16 GetAdcByChannel(uint8 chn)
{
    ADC_SelChannel(chn);

    return ADConverter();
}
